package com.woniuxy.woniufp.trade.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.woniufp.common.model.constant.UserConstant;
import com.woniuxy.woniufp.common.model.dto.trade.BorrowRecordDTO;
import com.woniuxy.woniufp.common.model.dto.trade.BorrowRecordQuery;
import com.woniuxy.woniufp.common.model.enums.BorrowStatusEnums;
import com.woniuxy.woniufp.common.model.exceptions.BusinessException;
import com.woniuxy.woniufp.common.model.result.Result;
import com.woniuxy.woniufp.common.model.result.enums.impl.BusinessCode;
import com.woniuxy.woniufp.common.model.utils.TokenUtiles;
import com.woniuxy.woniufp.common.model.utils.UniqueIDGenerator;
import com.woniuxy.woniufp.common.model.vo.trade.BorrowRecordVo;
import com.woniuxy.woniufp.common.model.vo.trade.BorrowSyncRecordVo;
import com.woniuxy.woniufp.common.model.vo.trade.Pages;
import com.woniuxy.woniufp.common.model.vo.user.TokenVo;
import com.woniuxy.woniufp.common.model.vo.user.UserInfoVo;
import com.woniuxy.woniufp.trade.clients.BankFeignClient;
import com.woniuxy.woniufp.trade.clients.UserFeignClient;
import com.woniuxy.woniufp.trade.entity.BorrowRecord;
import com.woniuxy.woniufp.trade.mapper.BorrowRecordMapper;
import com.woniuxy.woniufp.trade.service.IBorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class BorrowRecordServiceImpl implements IBorrowRecordService {

    @Autowired
    BorrowRecordMapper borrowRecordMapper ;
    @Autowired
    UserFeignClient userFeignClient ;

    @Autowired
    BankFeignClient bankFeignClient ;

    @Override
    public void addBorrowRecord(BorrowRecordDTO borrowRecordDTO) {
        BorrowRecord borrowRecord = new BorrowRecord();

        TokenVo tokenVo = TokenUtiles.getTokenVo();
        String id = tokenVo.getId();
        Result<UserInfoVo> result = userFeignClient.findById(Long.parseLong(id));
        UserInfoVo userInfoVo = result.getData();
        borrowRecord.setUserId(userInfoVo.getId());
        borrowRecord.setUserCode(userInfoVo.getUserCode());
        borrowRecord.setPeriod(borrowRecordDTO.getPeriod());
        borrowRecord.setInvestRate(new BigDecimal("10"));
        borrowRecord.setBorrowerRate(new BigDecimal("10"));
        borrowRecord.setCommissionRate(new BigDecimal("10"));
        borrowRecord.setRepaymentWay(borrowRecordDTO.getRepaymentWay());
        borrowRecord.setAmount(borrowRecord.getAmount());
        borrowRecord.setCreateDate(new Date());
        borrowRecord.setDescription("多多益善");
        borrowRecord.setBorrowStatus(BorrowStatusEnums.NEW.getCode());// 新建 、已同步、还款中 、已完成  使用枚举
        borrowRecord.setBorrowRecordNo(UniqueIDGenerator.generator(UserConstant.BORROW_CODE_PREFIX));

        String nameInfo = getNameInfo(userInfoVo.getIdentityCode(),userInfoVo.getUserName(),userInfoVo.getUserCode());
        borrowRecord.setName(nameInfo); //张三丰先生第5次借款

        borrowRecordMapper.insert(borrowRecord);
    }

    private String getNameInfo(String identityCode, String userName, String userCode) {
        StringBuffer sb = new StringBuffer();
        sb.append(userName);
        String num = identityCode.substring(identityCode.length()-2,identityCode.length()-1);
        String sex = Integer.parseInt(num) % 2 == 0?"女士":"先生";
        sb.append(sex);
        sb.append("第");
        BorrowRecord br = new BorrowRecord();
        br.setUserCode(userCode);
        int i = borrowRecordMapper.selectCountByUserCode(userCode);

        sb.append(i+1);
        sb.append("次借款");
        return  sb.toString();
    }

    @Override
    public Pages<BorrowRecordVo> queryBorrowRecord(Integer pageNum,
                                                   Integer pageSize,
                                                   BorrowRecordQuery borrowRecordQuery) {
        PageHelper.startPage(pageNum,pageSize);
        List<BorrowRecord> lists = borrowRecordMapper.selectBorrowRecordByCons(borrowRecordQuery);
        PageInfo<BorrowRecord> pageInfo = new PageInfo<>(lists);
        //封装 Pages对象
        Pages<BorrowRecordVo> pages = new Pages<>();
        pages.setPageSize(pageSize);
        pages.setPageNum(pageNum);
        pages.setTotal(pageInfo.getTotal());

        List<BorrowRecordVo> brvs = getBorrowRecordVoList(lists);
        pages.setList(brvs);

        return pages;
    }


    private List<BorrowRecordVo> getBorrowRecordVoList(List<BorrowRecord> lists) {
        List<BorrowRecordVo> brvs = BeanUtil.copyToList(lists, BorrowRecordVo.class);
        TokenVo tokenVo = TokenUtiles.getTokenVo();
        String id = tokenVo.getId();
        Result<UserInfoVo> result = userFeignClient.findById(Long.parseLong(id));
        UserInfoVo userInfoVo = result.getData();
        for (BorrowRecordVo brv :brvs) {
            brv.setUserName(userInfoVo.getUserName());
            brv.setIdentityCode(userInfoVo.getIdentityCode());
        }
        return brvs ;
    }

    @Override
    public String verifyStatus(Integer approveStatus, Long borrowRecordId) {
        //1. 更新 请求流水号 唯一值
        // 1.1 检查请求流水号 是否存在   根据借款申请的ID 查询借款的记录对象  判断 REQ_CODE 是否存在
        BorrowRecord borrowRecord = borrowRecordMapper.selectByPrimaryKey(borrowRecordId);
        //1.2  更新记录
        if (StringUtils.isEmpty(borrowRecord.getReqCode())) {
            //先生成 请求流水号
            String reqCode = UniqueIDGenerator.generator(UserConstant.REQUEST_CODE_PREFIX);
            borrowRecord.setReqCode(reqCode);
            //执行更新
            borrowRecordMapper.updateByPrimaryKey(borrowRecord);
        }
        //2. 封装远程调用 的参数对象数据
        BorrowSyncRecordVo borrowSyncRecordVo = BeanUtil.copyProperties(borrowRecord, BorrowSyncRecordVo.class);
        // 2.发送远程请求 （银行托管代理中心）
        Result result = bankFeignClient.syncBorrowRecord(borrowSyncRecordVo);
        //3 根据远程接口返回的结果 更新 borrow_reord 表中的  状态字段 status
        if (result.getCode() == 200) {
            //更新状态字段
            borrowRecord.setStatus(true);
            borrowRecordMapper.updateByPrimaryKey(borrowRecord);
            return "ok" ;
        }
        //如果审核失败  抛出错误异常  交给全局异常去处理
        throw new BusinessException(BusinessCode.BORROW_SYNC_ERROR);
    }




    /*public static void main(String[] args) {
        String id = "110101198807289209" ;
        String num = id.substring(id.length()-2,id.length()-1);
        System.out.println(num);
    }*/


}
